import {designPage, reactive, useRefs} from "plain-design-composition";
import data50 from '../../../data/data-50.json';
import {DemoRow} from "../../Demo/DemoRow";
import {$message, Button, ButtonGroup, Form, FormItem, Plc, PlcDate, PlcDateRange, PlcIndex, PlcInput, PlcNumber, Table} from "../../../../packages";
import {iTableNode} from "../../../../packages/components/Table/table/utils/table.utils";

export const demo1 = designPage(() => {

  const { refs, onRef } = useRefs({
    table: Table
  });

  const state = reactive({
    data: data50.slice(0, 5),
    editNodes: [] as iTableNode[],

    onDblClickRow(tableNode: iTableNode) {
      if (!tableNode.state.edit) {
        tableNode.enableEdit();
        state.editNodes.push(tableNode);
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <DemoRow title={'基本用法'}>
      <Form column={1}>
        <FormItem label="导出">
          <ButtonGroup style={{ margin: '4px 0' }}>
            <Button label="导出原始数据" onClick={() => console.log(refs.table!.methods.getSourceData())}/>
            <Button label="导出显示数据" onClick={() => refs.table!.methods.getShowData().then(val => console.log(val))}/>
          </ButtonGroup>
        </FormItem>
        <FormItem label={'编辑'}>
          <ButtonGroup disabled={state.editNodes.length === 0}>
            <Button onClick={state.saveEdit} label={'保存编辑'}/>
            <Button onClick={state.cancelEdit} label={'取消编辑'}/>
          </ButtonGroup>
        </FormItem>
      </Form>
      <Table
        data={state.data}
        onDblclickCell={state.onDblClickRow}
        ref={onRef.table}
      >
        <PlcIndex/>
        <Plc field="id" title="编号"/>
        <PlcInput field="name" title="文本框" required/>
        <PlcDate field="date" title="日期" required/>
      </Table>
    </DemoRow>
  );
});


export const demo2 = designPage(() => {

  const { refs, onRef } = useRefs({
    table: Table
  });

  const state = reactive({
    data: data50.slice(0, 5),
    editNodes: [] as iTableNode[],

    onDblClickRow(tableNode: iTableNode) {
      if (!tableNode.state.edit) {
        tableNode.enableEdit();
        state.editNodes.push(tableNode);
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <DemoRow title={'格式化'}>
      <Form column={1}>
        <FormItem label="导出">
          <ButtonGroup style={{ margin: '4px 0' }}>
            <Button label="导出原始数据" onClick={() => console.log(refs.table!.methods.getSourceData())}/>
            <Button label="导出显示数据" onClick={() => refs.table!.methods.getShowData().then(val => console.log(val))}/>
          </ButtonGroup>
        </FormItem>
        <FormItem label={'编辑'}>
          <ButtonGroup disabled={state.editNodes.length === 0}>
            <Button onClick={state.saveEdit} label={'保存编辑'}/>
            <Button onClick={state.cancelEdit} label={'取消编辑'}/>
          </ButtonGroup>
        </FormItem>
      </Form>
      <Table
        data={state.data}
        onDblclickCell={state.onDblClickRow}
        ref={onRef.table}
      >
        <PlcIndex/>
        <Plc field="id" title="编号"/>
        <PlcInput field="name" title="文本框" required/>
        <PlcDate field="date" title="日期" required/>
        <PlcDate field="date" title="日期(显示格式化)" width={150} required displayFormat="YYYY年MM月DD日"/>
        <PlcDate field="dateNumber" title="日期(值格式化)" width={150} required valueFormat="YYYYMMDD" displayFormat="YYYY年MM月DD日"/>
      </Table>
    </DemoRow>
  );
});


export const demo3 = designPage(() => {

  const { refs, onRef } = useRefs({
    table: Table
  });

  const state = reactive({
    data: data50.slice(0, 5),
    editNodes: [] as iTableNode[],

    onDblClickRow(tableNode: iTableNode) {
      if (!tableNode.state.edit) {
        tableNode.enableEdit();
        state.editNodes.push(tableNode);
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <DemoRow title={'多值'}>
      <Form column={1}>
        <FormItem label="导出">
          <ButtonGroup style={{ margin: '4px 0' }}>
            <Button label="导出原始数据" onClick={() => console.log(refs.table!.methods.getSourceData())}/>
            <Button label="导出显示数据" onClick={() => refs.table!.methods.getShowData().then(val => console.log(val))}/>
          </ButtonGroup>
        </FormItem>
        <FormItem label={'编辑'}>
          <ButtonGroup disabled={state.editNodes.length === 0}>
            <Button onClick={state.saveEdit} label={'保存编辑'}/>
            <Button onClick={state.cancelEdit} label={'取消编辑'}/>
          </ButtonGroup>
        </FormItem>
      </Form>
      <Table
        data={state.data}
        onDblclickCell={state.onDblClickRow}
        ref={onRef.table}
      >
        <PlcIndex/>
        <Plc field="id" title="编号"/>
        <PlcInput field="name" title="文本框" required/>
        <PlcDate field="dateList" title="日期" required multiple/>
        <PlcDate field="dateArrayJson" title="日期arrayjson" required multiple valueType="arrayjson"/>
        <PlcDate field="dateArrayString" title="日期arraystring" required multiple valueType="arraystring"/>
      </Table>
    </DemoRow>
  );
});


export const demo4 = designPage(() => {

  const { refs, onRef } = useRefs({
    table: Table
  });

  const state = reactive({
    data: data50.slice(0, 5),
    editNodes: [] as iTableNode[],

    onDblClickRow(tableNode: iTableNode) {
      if (!tableNode.state.edit) {
        tableNode.enableEdit();
        state.editNodes.push(tableNode);
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <DemoRow title={'日期范围选择'}>
      <Form column={1}>
        <FormItem label="导出">
          <ButtonGroup style={{ margin: '4px 0' }}>
            <Button label="导出原始数据" onClick={() => console.log(refs.table!.methods.getSourceData())}/>
            <Button label="导出显示数据" onClick={() => refs.table!.methods.getShowData().then(val => console.log(val))}/>
          </ButtonGroup>
        </FormItem>
        <FormItem label={'编辑'}>
          <ButtonGroup disabled={state.editNodes.length === 0}>
            <Button onClick={state.saveEdit} label={'保存编辑'}/>
            <Button onClick={state.cancelEdit} label={'取消编辑'}/>
          </ButtonGroup>
        </FormItem>
      </Form>
      <Table
        data={state.data}
        onDblclickCell={state.onDblClickRow}
        ref={onRef.table}
      >
        <PlcIndex/>
        <Plc field="id" title="编号"/>
        <PlcInput field="name" title="文本框" required/>
        <PlcDateRange
          startField="startDate"
          startTitle="开始日期"
          endField="endDate"
          endTitle="结束日期"
          startAttrs={{ required: true }}
        />
        <PlcNumber field="num" title="数字"/>
      </Table>
    </DemoRow>
  );
});


export const demo5 = designPage(() => {

  const { refs, onRef } = useRefs({
    table: Table
  });

  const state = reactive({
    data: data50.slice(0, 5),
    editNodes: [] as iTableNode[],

    onDblClickRow(tableNode: iTableNode) {
      if (!tableNode.state.edit) {
        tableNode.enableEdit();
        state.editNodes.push(tableNode);
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <DemoRow title={'日期时间范围选择'}>
      <Form column={1}>
        <FormItem label="导出">
          <ButtonGroup style={{ margin: '4px 0' }}>
            <Button label="导出原始数据" onClick={() => console.log(refs.table!.methods.getSourceData())}/>
            <Button label="导出显示数据" onClick={() => refs.table!.methods.getShowData().then(val => console.log(val))}/>
          </ButtonGroup>
        </FormItem>
        <FormItem label={'编辑'}>
          <ButtonGroup disabled={state.editNodes.length === 0}>
            <Button onClick={state.saveEdit} label={'保存编辑'}/>
            <Button onClick={state.cancelEdit} label={'取消编辑'}/>
          </ButtonGroup>
        </FormItem>
      </Form>
      <Table
        data={state.data}
        onDblclickCell={state.onDblClickRow}
        ref={onRef.table}
      >
        <PlcIndex/>
        <Plc field="id" title="编号"/>
        <PlcInput field="name" title="文本框" required/>
        <PlcDateRange
          startField="startDatetime"
          startTitle="开始日期"
          endField="endDatetime"
          endTitle="结束日期"
          datetime
          startAttrs={{ required: true }}
        />
        <PlcNumber field="num" title="数字"/>
      </Table>
    </DemoRow>
  );
});
